
package logic.actions.delete;

import java.lang.reflect.ParameterizedType;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import logic.actions.SEISaudeAction;
import logic.beans.DBElementIF;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;

import controller.SEISaudeDefaultFacade;

public class DeleteElementAction<E extends DBElementIF> extends SEISaudeAction {
	@SuppressWarnings("unchecked")
	@Override
	public ActionForward execute(ActionMapping mapping,ActionForm form,
			HttpServletRequest request,HttpServletResponse response) throws Exception {
		if (isUserChecked() && !checkUserLogged(request)) return mapping.findForward("login");
		
		Class<E> elementClass = (Class<E>)((ParameterizedType)this.getClass().getGenericSuperclass()).getActualTypeArguments()[0];
		SEISaudeDefaultFacade<E,Long> facade = SEISaudeDefaultFacade.getInstance(elementClass);
		ActionMessages errors = getErrors(request);
		ActionMessages messages = getMessages(request);
		
		try {
			if (request.getParameter("eID") != null) {
				facade.removeElement(Long.parseLong(request.getParameter("eID")));
				messages.add("delete success",new ActionMessage("element.delete.success"));
			} else {
				List<E> elementList = facade.getAllElements();
				List<Long> checkedElementsIDList = new ArrayList<Long>();
				Iterator<E> elementsIt = elementList.iterator();
				while (elementsIt.hasNext()) {
					Long eachId = elementsIt.next().getId();
					String eachCheckedElement = request.getParameter("e" + eachId + "checkbox");
					if (eachCheckedElement != null) {
						checkedElementsIDList.add(eachId);
					}
				}
				facade.removeElements(checkedElementsIDList);
				messages.add("delete success",new ActionMessage("element.delete.success"));
			}
		} catch (Exception ex) {
			facade.clearCurrentSession();
			errors.add("delete error",new ActionMessage("element.delete.error",ex.getMessage()));
		}
		
		saveErrors(request,errors);
		saveMessages(request,messages);
		
		return mapping.findForward(request.getParameter("fwd"));
	}
}
